package com.pointcircle.core.web;

import java.io.Serializable;

import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pointcircle.core.JpaBaseEntity;
import com.pointcircle.core.web.annotation.ApiPermissionConfig;

@Validated
public interface IAddRest<T extends JpaBaseEntity<ID>, ID extends Serializable, 
	EV extends EntityVo<T, ID>, FV extends FormVo<ID>> 
	extends IFormRest<T, ID, EV, FV> {

	@SuppressWarnings("unchecked")
	@PostMapping(value = "/add")
	@ApiPermissionConfig("add")
	default RestResponseElement add(@RequestBody String json) throws Exception {
		try {
			T entity = this.generateEntity();
			ObjectMapper mapper = new ObjectMapper();
			FV form = mapper.readValue(json, this.getFormVoClass());
			IAddRest<T, ID, EV, FV> self = (IAddRest<T, ID, EV, FV>) this.getSelfComponent();
			self.processAddEntity(form, entity);
			return this.createRestResponseElement(entity);
		} catch(Exception e) {
			throw new RestException(e);
		}
	}
	
	void processAddEntity(@Valid FV form, T entity) throws Exception;
}
